package com.nuoniu.sibanyun.service.erp.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.entity.erp.ErpDespatchType;
import com.nuoniu.sibanyun.mapper.erp.ErpDespatchTypeMapper;
import com.nuoniu.sibanyun.service.erp.IErpAccountService;
import com.nuoniu.sibanyun.service.erp.IErpDespatchTypeService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 发运方式 服务实现类
 * </p>
 *
 * @author 小啊刚
 * @since 2020-12-08
 */
@Service
public class ErpDespatchTypeServiceImpl extends ServiceImpl<ErpDespatchTypeMapper, ErpDespatchType> implements IErpDespatchTypeService {

    @Autowired
    private IErpAccountService accountService;

    @Override
    public Page<ErpDespatchType> pageList(Page pages, ErpDespatchType despatchType) {
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper<ErpDespatchType> queryWrapper = new QueryWrapper();
        queryWrapper.eq("company_id", userInfo.getCompanyId());
        queryWrapper.eq("account_id", accountService.getCurrentAccountId());
        if(StringUtils.isNotBlank(despatchType.getSearchKey())) {
            queryWrapper.and(wrapper -> wrapper.likeRight("code", despatchType.getSearchKey()).or().like("name", despatchType.getSearchKey()));
        }
        Page page = page(pages, queryWrapper);
        return page;
    }

    @Override
    public void saveDespatchType(ErpDespatchType despatchType) {
        UserInfo userInfo = UserThreadLocal.get();
        ErpDespatchType despatchByName = baseMapper.getByName(despatchType.getName(), userInfo.getCompanyId());
        if(despatchByName != null && (despatchType.getId() == null || !despatchType.getId().equals(despatchByName.getId()))) {
            throw new NuoNiuException("名称已存在");
        }

        ErpDespatchType despatchByCode = baseMapper.getByCode(despatchType.getCode(), userInfo.getCompanyId());
        if(despatchByCode != null && (despatchType.getId() == null || !despatchType.getId().equals(despatchByCode.getId()))) {
            throw new NuoNiuException("编码已存在");
        }

        if(despatchType.getId() == null) {
            despatchType.setAccountId(accountService.getCurrentAccountId());
            despatchType.setCompanyId(userInfo.getCompanyId());
        }


        this.saveOrUpdate(despatchType);
    }
}
